/**
 * 
 */
package com.kgcx.common.mqtt;

import org.eclipse.paho.client.mqttv3.IMqttDeliveryToken;
import org.eclipse.paho.client.mqttv3.MqttCallback;
import org.eclipse.paho.client.mqttv3.MqttMessage;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Component;

/**
 * @author 袁进勇
 *
 */
@Component
public class MqttProducerCallback implements MqttCallback {
    private static final Logger LOG = LoggerFactory.getLogger(MqttProducerCallback.class);

    /*
     * (non-Javadoc)
     * 
     * @see org.eclipse.paho.client.mqttv3.MqttCallback#connectionLost(java.lang.Throwable)
     */
    @Override
    public void connectionLost(Throwable throwable) {
        LOG.warn("断开MQTT连接！", throwable);
    }

    /*
     * (non-Javadoc)
     * 
     * @see org.eclipse.paho.client.mqttv3.MqttCallback#messageArrived(java.lang.String,
     * org.eclipse.paho.client.mqttv3.MqttMessage)
     */
    @Override
    public void messageArrived(String topic, MqttMessage message) throws Exception {
        // 注意：收到消息的处理代码中，所有异常必须捕获，否则抛给MQTT框架会导致连接断开。

        try {
            LOG.debug(String.format("收到MQTT消息。topic=%s，id=%d，qos=%d，payload=%s。", topic, message.getId(),
                    message.getQos(), new String(message.getPayload())));
        } catch (Exception e) {
            LOG.error(String.format("处理MQTT消息异常！topic=%s，id=%d，qos=%d", topic, message.getId(), message.getQos()));
        }
    }

    /*
     * (non-Javadoc)
     * 
     * @see
     * org.eclipse.paho.client.mqttv3.MqttCallback#deliveryComplete(org.eclipse.paho.client.mqttv3.IMqttDeliveryToken)
     */
    @Override
    public void deliveryComplete(IMqttDeliveryToken token) {
        // try {
        // String topics = ArrayUtil.join(token.getTopics(), ",");
        // MqttMessage message = token.getMessage();
        // LOG.debug(String.format("发送MQTT消息完成。topics=%s，id=%d", topics == null ? "" : topics, message.getId()));
        // } catch (Exception e) {
        // LOG.error("发送MQTT消息异常！", e);
        // }
    }

}
